package com.lge.remoteshot.network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import android.util.Log;

import com.lge.remoteshot.camera.CameraActivity;

public class ServerPreviewThread extends Thread {
	private CameraActivity activity;

	private DatagramSocket dSock;

	private InetAddress host;
	private byte[] buffer = new byte[4096 * 5];
	private boolean runThread = true;

	public ServerPreviewThread(CameraActivity activity) {
		// TODO Auto-generated constructor stub
		this.activity = activity;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			dSock = new DatagramSocket(ServerManager.SERVER_PREVIEW_PORT);
			while (runThread) {
				DatagramPacket recvPacket = new DatagramPacket(buffer, 0, buffer.length);
				dSock.receive(recvPacket);
				host = recvPacket.getAddress();
					activity.setReceiveFrame(recvPacket.getData());
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"serverSocketThread:run:SocketException" + e.toString() + e.getMessage());
			runThread = false;
			if (dSock != null)
				dSock.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG,
					"serverSocketThread:run:IOException" + e.toString() + e.getMessage());
			runThread = false;
			if (dSock != null)
				dSock.close();
		}

	}

	public void sendAction(String action) {
		try {
			if (host != null && dSock != null) {
				byte[] temp = action.getBytes();
				DatagramPacket sendPacket = new DatagramPacket(temp, 0, temp.length, host,
						ServerManager.SERVER_PREVIEW_PORT);
				dSock.send(sendPacket);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.d(CameraActivity.TAG, "serverSocketThread:sendAction:IOException" + e.toString()
					+ e.getMessage());
		}
	}

	public void stopThread() {
		runThread = false;
		if (dSock != null)
			dSock.close();
	}
}